<template>
  <el-form ref="gfrom" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" type="password"></el-input>
    </el-form-item>

    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="form.mobile"></el-input>
    </el-form-item>

    <el-form-item label="验证码" prop="code">
      <el-input v-model="form.code"></el-input>
      <el-button @click="getcode">点击验证</el-button>
    </el-form-item>
    <el-form-item>
      <!-- 全局验证 -->
      <el-button @click="submit">验证全局</el-button>
      <!-- 局部验证 -->
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  methods: {
    //   全局验证
    submit () {
      this.$refs.gfrom.validate(result => {
        console.log(result)
      })
    },
    // 局部验证
    getcode () {
      this.$refs.gfrom.validateField(['password'], errorMsg => {
        console.log(errorMsg)
      })
    }
  },
  data () {
    return {
      form: {
        password: '',
        mobile: ''
      },
      rules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // value:当前验证项的值
              // 验证成功：callback()
              // 验证失败：callback(new Error('错误信息'))
              let req = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              let bool = req.test(value)
              if (bool) {
                callback()
              } else {
                callback(new Error('手机格式不对'))
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  }
}
</script>

<style></style>
